#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from django.shortcuts import render;
from django.http import HttpResponse, JsonResponse;
import json;
from app_account.models import *;
from common.page_vo import *;
from common import md5_util;
from datetime import datetime;

'''
Account views
'''
__author__ = "HymanHu";

# Create your views here.

# 127.0.0.1/helloWorld ---- get
def hello_world(reques):
    return HttpResponse("<h3>Hello Wolrd!</h3>");

# 127.0.0.1/helloWorldPage ---- get
def hello_world_page(request):
    content = {};
    content["name"] = "HymanHu";
    return render(request, "account/helloWorld.html", content);

# 127.0.0.1/register ---- get 加载注册页面
def register(request):
    if request.method == "GET":
        return render(request, "account/register.html");
    else:
        return JsonResponse(Result(500, "Unsupport request type %s" % (request.method)).__dict__, safe=False);

# 127.0.0.1/user ---- post 进行用户注册{"userName":"hujiang1","password":"111111"}
def user(request):
    if request.method == "GET":
        pass;
    elif request.method == "POST":
        user_dict = json.loads(request.body);
        user_name = user_dict.get("userName");
        password = user_dict.get("password");

        # 查询 User name 是否重复
        user_temp = User.objects.filter(user_name=user_name).first();
        if user_temp:
            return JsonResponse(Result(500, "User name is repeat.").__dict__, safe=False);
        else:
            # 用户名不重复，则新增并返回正确的result
            user = User(user_name=user_name, password=md5_util.get_md5(password), create_date=datetime.now());
            user.save();
            return JsonResponse(Result(200, "Register success.", user.user_dict()).__dict__, safe=False);
    else:
        return JsonResponse(Result(500, "Unsupport request type %s" % (request.method)).__dict__, safe=False);

# 127.0.0.1/login ---- get
def login_page(request):
    return render(request, "account/login.html");

# 127.0.0.1/loginUser?userName=admin&password=111111 ---- get
def login(request):
    if request.method == "GET":
        user_name = request.GET.get("userName");
        password = request.GET.get("password");
        user = User.objects.filter(user_name=user_name, password=md5_util.get_md5(password)).first();
        if user:
            request.session['user'] = user.user_dict();
            return JsonResponse(Result(200, "Login success.").__dict__, safe=False);
        else:
            return JsonResponse(Result(500, "User name or password error.").__dict__, safe=False);
    else:
        return JsonResponse(Result(500, "Unsupport request type %s" % (request.method)).__dict__, safe=False);

# 127.0.0.1/dashboard ---- get
def dashboard_page(request):
    return render(request, "account/dashboard.html");
